package com.zjitc.controller;

import com.github.pagehelper.PageInfo;
import com.sun.org.apache.bcel.internal.generic.RET;
import com.sun.org.apache.regexp.internal.RE;
import com.zjitc.model.Category;
import com.zjitc.model.History;
import com.zjitc.model.Product;
import com.zjitc.service.CategoryService;
import com.zjitc.service.ProductService;
import com.zjitc.utils.CookieUtils;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import sun.management.snmp.AdaptorBootstrap.DefaultValues;
import sun.security.provider.MD2;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/19 16:19
 * @description:
 */
@Controller
@RequestMapping("/product")
public class ProductController {
  private static final Integer count=12;
  @Autowired
  private ProductService productService;

  @Autowired
  private CategoryService categoryService;

  @RequestMapping("/asCategoryFindProduct")
  public String findProduct(@RequestParam(name = "cid")String cid,
      @RequestParam(name = "pageNum",defaultValue = "1")Integer pageNum,
      Model model){
    List<Product> products=productService.findByCid(cid,pageNum,count);
    PageInfo<Product> pageInfo=new PageInfo<Product>(products);
    model.addAttribute("page",pageInfo);
    model.addAttribute("cid",cid);
    model.addAttribute("products",products);
    return "/jsp/product_list.jsp";
  }


  @RequestMapping("/getProductInfo")
  public String info(@RequestParam(name = "pid") String pid,
      HttpSession session) {
    Product product  = productService.findProductInfo(pid);
    Category category = categoryService.findByCid(product.getCid());
    history(session,product);
    product.setCategory(category);
    session.setAttribute("bean",product);
    return "/jsp/product_info.jsp";
  }

  public void history(HttpSession session,Product product){
    Object h= session.getAttribute("history");
    History history=null;
    if(h==null){
      history=new History();
      session.setAttribute("history",history);
    }else{
      history=(History)h;
    }
    history.add(product);
  }
}
